package top.yokey.shopai.order.activity;

import android.view.View;
import android.view.inputmethod.EditorInfo;

import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.Toolbar;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.google.android.material.tabs.TabLayout;
import com.jeremyliao.liveeventbus.LiveEventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import top.yokey.shopai.R;
import top.yokey.shopai.order.adapter.OrderListAdapter;
import top.yokey.shopai.order.viewmodel.OrderListVM;
import top.yokey.shopai.zcom.App;
import top.yokey.shopai.zcom.adapter.ViewPagerAdapter;
import top.yokey.shopai.zcom.arouter.ARoutePath;
import top.yokey.shopai.zcom.base.BaseActivity;
import top.yokey.shopai.zcom.help.DialogHelp;
import top.yokey.shopai.zcom.help.ToastHelp;
import top.yokey.shopai.zcom.other.Constant;
import top.yokey.shopai.zcom.util.JsonUtil;
import top.yokey.shopai.zcom.view.PullRefreshView;
import top.yokey.shopai.zsdk.bean.OrderBean;
import top.yokey.shopai.zsdk.data.OrderPinGouData;
import top.yokey.shopai.zsdk.data.RetreatData;

@Route(path = ARoutePath.ORDER_LIST)
public class OrderListActivity extends BaseActivity {

    private final int[] page = new int[5];
    private final String[] type = new String[5];
    @SuppressWarnings("unchecked")
    private final ArrayList<OrderBean>[] arrayList = new ArrayList[5];
    private final OrderListAdapter[] adapter = new OrderListAdapter[5];
    private final PullRefreshView[] mainPullRefreshView = new PullRefreshView[5];
    @Autowired(name = Constant.DATA_POSITION)
    int position;
    private Toolbar mainToolbar = null;
    private AppCompatEditText toolbarEditText = null;
    private AppCompatImageView toolbarImageView = null;
    private TabLayout mainTabLayout = null;
    private ViewPager mainViewPager = null;
    private String keyword = "";
    private OrderListVM vm = null;

    @Override
    public void initView() {

        setContentView(R.layout.activity_order_list);
        mainToolbar = findViewById(R.id.mainToolbar);
        toolbarEditText = findViewById(R.id.toolbarEditText);
        toolbarImageView = findViewById(R.id.toolbarImageView);
        mainTabLayout = findViewById(R.id.mainTabLayout);
        mainViewPager = findViewById(R.id.mainViewPager);

    }

    @Override
    public void initData() {

        setToolbar(mainToolbar);
        observeKeyborad(R.id.mainLinearLayout);
        position = getIntent().getIntExtra(Constant.DATA_POSITION, 0);
        toolbarEditText.setHint(R.string.pleaseInputOrderSnOrTitle);
        toolbarImageView.setImageResource(R.drawable.ic_action_search);
        type[0] = "";
        type[1] = "state_new";
        type[2] = "state_pay";
        type[3] = "state_send";
        type[4] = "state_noeval";
        List<String> titleList = new ArrayList<>();
        titleList.add(getString(R.string.all));
        titleList.add(getString(R.string.waitPay));
        titleList.add(getString(R.string.waitDeliver));
        titleList.add(getString(R.string.waitReceive));
        titleList.add(getString(R.string.waitEvaluate));
        List<View> viewList = new ArrayList<>();
        viewList.add(getLayoutInflater().inflate(R.layout.include_pull_refresh_view, null));
        viewList.add(getLayoutInflater().inflate(R.layout.include_pull_refresh_view, null));
        viewList.add(getLayoutInflater().inflate(R.layout.include_pull_refresh_view, null));
        viewList.add(getLayoutInflater().inflate(R.layout.include_pull_refresh_view, null));
        viewList.add(getLayoutInflater().inflate(R.layout.include_pull_refresh_view, null));
        for (int i = 0; i < viewList.size(); i++) {
            page[i] = 1;
            arrayList[i] = new ArrayList<>();
            adapter[i] = new OrderListAdapter(arrayList[i]);
            mainPullRefreshView[i] = viewList.get(i).findViewById(R.id.mainPullRefreshView);
            mainTabLayout.addTab(mainTabLayout.newTab().setText(titleList.get(i)));
            mainPullRefreshView[i].setAdapter(adapter[i]);
        }
        App.get().setTabLayout(mainTabLayout, mainViewPager, new ViewPagerAdapter(viewList, titleList));
        mainTabLayout.setTabMode(TabLayout.MODE_FIXED);
        mainViewPager.setCurrentItem(position);
        vm = getVM(OrderListVM.class);
        page[position] = 1;
        getData();

    }

    @Override
    public void initEvent() {

        toolbarImageView.setOnClickListener(view -> {
            keyword = Objects.requireNonNull(toolbarEditText.getText()).toString();
            page[position] = 1;
            hideKeyboard();
            getData();
        });

        toolbarEditText.setOnEditorActionListener((textView, i, keyEvent) -> {
            if (i == EditorInfo.IME_ACTION_SEARCH) {
                keyword = Objects.requireNonNull(toolbarEditText.getText()).toString();
                page[position] = 1;
                hideKeyboard();
                getData();
            }
            return false;
        });

        mainViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position1) {
                position = position1;
                if (arrayList[position].size() == 0) {
                    page[position] = 1;
                    getData();
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        for (int i = 0; i < mainPullRefreshView.length; i++) {
            final int pos = i;
            mainPullRefreshView[pos].setOnClickListener(view -> {
                if (mainPullRefreshView[pos].isError() || arrayList[pos].size() == 0) {
                    page[pos] = 1;
                    getData();
                }
            });
        }

        for (PullRefreshView pullRefreshView : mainPullRefreshView) {
            pullRefreshView.setOnRefreshListener(new PullRefreshView.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    page[position] = 1;
                    getData();
                }

                @Override
                public void onLoadMore() {
                    getData();
                }
            });
        }

        for (OrderListAdapter listAdapter : adapter) {
            listAdapter.setOnItemClickListener(new OrderListAdapter.OnItemClickListener() {
                @Override
                public void onPay(int position, OrderBean bean) {
                    App.get().start(ARoutePath.ORDER_PAY, Constant.DATA_SN, bean.getPaySn());
                }

                @Override
                public void onClick(int position, OrderBean bean) {
                    detailed(bean.getOrderList().get(0).getOrderId());
                }

                @Override
                public void onItemClick(int position, int itemPosition, OrderBean.OrderListBean bean) {
                    detailed(bean.getOrderId());
                }

                @Override
                public void onItemGoodsClick(int position, int itemPosition, OrderBean.OrderListBean bean) {
                    detailed(bean.getOrderId());
                }

                @Override
                public void onOption(int position, int itemPosition, OrderBean.OrderListBean bean) {
                    if (bean.getOrderState().equals("30")) {
                        logistics(bean.getOrderId());
                        return;
                    }
                    if (bean.getOrderState().equals("40")) {
                        delete(bean.getOrderId());
                    }
                }

                @Override
                public void onOpera(int position, int itemPosition, OrderBean.OrderListBean bean) {
                    if (bean.getPinGouInfo() != null && bean.getOrderState().equals("20")) {
                        OrderPinGouData data = new OrderPinGouData();
                        data.setPinGouId(bean.getPinGouInfo().getLogId());
                        data.setBuyerId(bean.getPinGouInfo().getBuyerId());
                        App.get().startOrderPinGou(data);
                        return;
                    }
                    switch (bean.getOrderState()) {
                        case "0":
                            //删除订单
                            delete(bean.getOrderId());
                            break;
                        case "10":
                            //取消订单
                            cancel(bean.getOrderId());
                            break;
                        case "20":
                            if (bean.getLockState() == null || bean.getLockState().equals("0")) {
                                //申请退款
                                refund(bean.getOrderId());
                            } else {
                                //订单详细
                                detailed(bean.getOrderId());
                            }
                            break;
                        case "30":
                            if (bean.getLockState() == null || bean.getLockState().equals("0")) {
                                //确认收货
                                receive(bean.getOrderId());
                            } else {
                                //订单详细
                                detailed(bean.getOrderId());
                            }
                            break;
                        case "40":
                            if (bean.isIfEvaluation()) {
                                evaluate(bean.getOrderId());
                                return;
                            }
                            if (bean.isIfEvaluationAgain()) {
                                evaluateAgain(bean.getOrderId());
                                return;
                            }
                            if (!bean.isIfEvaluation() && !bean.isIfEvaluationAgain()) {
                                if (bean.isIfDeliver()) {
                                    logistics(bean.getOrderId());
                                    return;
                                }
                                detailed(bean.getOrderId());
                            }
                            break;
                    }
                }
            });
        }

    }

    @Override
    public void initObserve() {

        vm.getOrderLiveData().observe(this, list -> {
            if (page[position] == 1) arrayList[position].clear();
            page[position] = page[position] + 1;
            arrayList[position].addAll(list);
            mainPullRefreshView[position].setComplete();
        });

        vm.getHasMoreLiveData().observe(this, bool -> mainPullRefreshView[position].setCanLoadMore(bool));

        vm.getCancelLiveData().observe(this, string -> {
            ToastHelp.get().showSuccess();
            page[position] = 1;
            getData();
        });

        vm.getDeleteLiveData().observe(this, string -> {
            ToastHelp.get().showSuccess();
            page[position] = 1;
            getData();
        });

        vm.getReceiveLiveData().observe(this, string -> {
            ToastHelp.get().showSuccess();
            page[position] = 1;
            getData();
        });

        vm.getErrorLiveData().observe(this, bean -> {
            if (bean.getCode() == 1) {
                if (arrayList[position] != null && arrayList[position].size() != 0) {
                    ToastHelp.get().show(bean.getReason());
                } else {
                    mainPullRefreshView[position].setError(bean.getReason());
                }
            } else {
                ToastHelp.get().show(bean.getReason());
            }
        });

        LiveEventBus.get(Constant.DATA_REFRESH, boolean.class).observe(this, bool -> {
            page[position] = 1;
            getData();
        });

    }

    //自定义方法

    private void getData() {

        mainPullRefreshView[position].setLoad();
        vm.getOrderList(type[position], keyword, page[position] + "");

    }

    private void delete(String orderId) {

        DialogHelp.get().query(get(), R.string.confirmSelection, R.string.deleteOrder, null, view -> vm.deleteOrder(orderId));

    }

    private void cancel(String orderId) {

        DialogHelp.get().query(get(), R.string.confirmSelection, R.string.cancelOrder, null, view -> vm.cancelOrder(orderId));

    }

    private void receive(String orderId) {

        DialogHelp.get().query(get(), R.string.confirmSelection, R.string.confirmReceive, null, view -> vm.receiveOrder(orderId));

    }

    private void logistics(String orderId) {

        App.get().start(ARoutePath.ORDER_LOGISTICS, Constant.DATA_ID, orderId);

    }

    private void refund(String orderId) {

        RetreatData data = new RetreatData();
        data.setOrderId(orderId);
        App.get().start(ARoutePath.RETREAT_REFUND_ALL, Constant.DATA_JSON, JsonUtil.toJson(data));

    }

    private void detailed(String orderId) {

        App.get().start(ARoutePath.ORDER_DETAILED, Constant.DATA_ID, orderId);

    }

    private void evaluate(String orderId) {

        App.get().start(ARoutePath.ORDER_EVALUATE, Constant.DATA_ID, orderId);

    }

    private void evaluateAgain(String orderId) {

        App.get().start(ARoutePath.ORDER_EVALUATE_AGAIN, Constant.DATA_ID, orderId);

    }

}
